package com.lizemin.inputoutput.filter;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author lzm
 * @date 2025/4/4 16:25
 * @description
 */
@Slf4j
public class FixedRequestWrapper extends HttpServletRequestWrapper {

    public FixedRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 重写获取请求体的方法，我们让每个接口都收到固定的请求体
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        ServletInputStream inputStream = super.getInputStream();
        String reqBody = IoUtil.read(inputStream, StandardCharsets.UTF_8);
        log.info("请求体中的内容为：\n{}", reqBody);
        return new CustomerServletInputStream();
    }

    static class CustomerServletInputStream extends ServletInputStream {
        String basePath = System.getProperty("user.dir");
        FileInputStream fis;

        {
            try {
                fis = new FileInputStream(basePath + "/src/main/resources/body.txt");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }


        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener listener) {

        }

        @Override
        public int read() throws IOException {
            return fis.read();
        }

    }


}
